import React, {
  useEffect,
  useRef,
  useState,
  useCallback,
  useLayoutEffect,
} from "react";
import "./Home.css";

function Home() {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isScrolling, setIsScrolling] = useState(false);
  const [iframeKey, setIframeKey] = useState(0);
  const [needPostMessage, setNeedPostMessage] = useState(false); // 标记 onLoad 后是否需要 postMessage

  const iframeRef = useRef(null);
  const containerRef = useRef(null);
  const activeIndexRef = useRef(0);

  // 更新ref值
  useEffect(() => {
    setTimeout(() => {
      activeIndexRef.current = activeIndex;
    }, 1000); // 延迟1秒更新activeIndexRef
  }, [activeIndex]);

  // 调用此方法可让 iframe reload
  const reloadIframe = () => setIframeKey(prev => prev + 1);

  const updateData = (index) => {
    console.log("Proceeding with normal scroll");
    setIsScrolling(true);
    setActiveIndex(index);
    // 立即更新ref值
    activeIndexRef.current = index;

    if (containerRef.current) {
      containerRef.current.scrollTo({
        top: index * window.innerHeight,
        behavior: "smooth",
      });
    }

    // 滚动动画完成后重置状态 - 减少延迟

    setIsScrolling(false);
  }

  // 滚动到指定section
  const scrollToSection = useCallback(
    (index) => {


      if (index < 0 || isScrolling) {
        console.log("Early return - condition not met");
        return;
      }

      // 如果当前要到第一页，reload iframe 并标记需要 postMessage
      if (index === 0) {
        setNeedPostMessage(true);
        reloadIframe();
      }

      // 如果当前在第一屏且要离开，显示提示
      if (index === 0 || index === 1) {

        const iframe = iframeRef.current;

        if (iframe) {
          if (index === 0) {

            updateData(index)
            setTimeout(() => {
              iframe.contentWindow.postMessage({
                type: 'trigger-keyboard' // 自定义消息类型
              }, '*');
            }, 1500);
            // postMessage 逻辑已移到 onLoad
          } else {
            // 发送消息给子页面
            iframe.contentWindow.postMessage({
              type: 'trigger-keyboard' // 自定义消息类型
            }, '*');
            setTimeout(() => {
              updateData(index)
            }, 2000);
          }


        }


      } else {
        updateData(index)
      }


    },
    [isScrolling]
  );

  // 处理键盘事件
  const handleKeyDown = useCallback(
    (e) => {
      // 添加详细的调试信息到调试面板
      const debugInfo = `键盘事件: ${e.key}, keyCode: ${e.keyCode}, code: ${e.code}`;
      console.log(debugInfo, '=====debugInfo');

      if (isScrolling) return;


      let newIndext = activeIndexRef.current;

      if (newIndext > 0 && newIndext < 3) {

        scrollToSection(newIndext);
      }
    },
    [isScrolling]
  );

  useLayoutEffect(() => {

    // 父页面代码
    window.addEventListener('message', (event) => {
      // 检查消息类型
      if (event.data.type === 'keydown-event') {
        // console.log('收到子页面的按键事件:', event.data.key);
        // console.log('是否按下 Ctrl:', event.data.ctrlKey);
        // handleKeyDown(event.data)
      }
    });
    // 清理事件监听器
    return () => {
      // document.removeEventListener("keydown", handleKeyDown, true);
      window.removeEventListener("keydown", handleKeyDown, true);
    };
  }, []);



  return (
    <div
      className="home-container"
      ref={containerRef}
    >
      {/* 切换屏幕按钮，固定在右下角 */}
      <button
        style={{
          position: 'fixed',
          right: 24,
          bottom: 24,
          zIndex: 1000,
          padding: '12px 24px',
          fontSize: '16px',
          borderRadius: '8px',
          background: '#007bff',
          color: '#fff',
          border: 'none',
          cursor: 'pointer',
          boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
        }}
        onClick={e => {
          e.stopPropagation(); // 防止冒泡到容器点击
          const nextIndex = (activeIndexRef.current + 1) % 3;
          debugger
          scrollToSection(nextIndex);
          // const iframe = iframeRef.current;

          // if (iframe) {
          //   // 发送消息给子页面
          //   iframe.contentWindow.postMessage({
          //     type: 'trigger-keyboard' // 自定义消息类型
          //   }, '*');
          // }

        }}
      >
        下一屏
        {activeIndexRef.current}
        {activeIndex}
      </button>
      <div className={`section section-1`}>
        <div className="iframe-wrapper">

            <iframe
              // key={iframeKey}
              ref={iframeRef}
              src="/page/index.html"
              onLoad={() => {
                if (needPostMessage) {
                  setNeedPostMessage(false);
                  const iframe = iframeRef.current;
                  if (iframe && iframe.contentWindow) {
                    iframe.contentWindow.postMessage({
                      type: 'trigger-keyboard'
                    }, '*');
                  }
                }
              }}
            />
          
        </div>
      </div>
      <div className={`section section-2${activeIndex === 1 ? "" : " shrink"}`}>
        <h1>第二屏</h1>
        <p>使用键盘方向键、Page Up/Down、空格键或鼠标滚轮进行切换</p>
      </div>
      <div className={`section section-3${activeIndex === 2 ? "" : " shrink"}`}>
        <h1>第三屏</h1>
        <p>移动端支持触摸滑动切换</p>
      </div>
    </div >
  );
}



const aaaa = {}

export default Home;
